package com.unipay.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.unipay.enums.PaymentStatusEnum;
import com.unipay.enums.PaymentTypeEnum;
import com.unipay.enums.RefundStatusEnum;
import com.unipay.model.order.OrderInfo;
import com.unipay.model.order.PaymentInfo;
import com.unipay.model.order.RefundInfo;
import com.unipay.order.service.OrderService;
import com.unipay.order.service.PaymentService;
import com.unipay.order.service.RefundInfoService;
import com.unipay.order.service.WeixinService;
import com.unipay.order.utils.ConstantPropertiesUtils;
import com.unipay.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Chenmy
 * @Date 2023/7/18 21:57
 * @Desc TODO
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RefundInfoService refundInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    // TODO 根据订单号下单，生成支付链接
    @Override
    public Map createNative(Long orderId) {
        try {
            // 0、Redis缓存右该条信息，直接返回
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (null != payMap) return payMap;

            // 1、根据ID，获取订单信息
            OrderInfo order = orderService.getById(orderId);
            // 2、保存，交易记录
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());

            // 3、设置参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());    // ???????????????
            String body = order.getReserveDate() + "就诊" + order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            // ---费用，设置---
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");
            // 4、HTTPClient来根据URL，访问第三方接口，并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // 5、client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            // 6、返回第三方的数据
            // String xmlParam = client.getXmlParam();
            String xmlParam = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlParam);
            // 7、封装，返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            // TODO 二维码地址
            map.put("codeUrl", resultMap.get("code_url"));
            if (null != resultMap.get("result_code")) {
                // TODO 微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 1000, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }
    }

    // TODO 请求第三方微信接口，查询 “支付状态“
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            OrderInfo orderInfo = orderService.getById(orderId);
            //（1）封装参数
            Map paraMap = new HashMap<>();
            paraMap.put("appid", ConstantPropertiesUtils.APPID);
            paraMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paraMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr());     // ??????????????
            //（2）设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paraMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //（3）返回：第三方数据，转map
            String xmlParam = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlParam);
            //（4）返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }

    // 微信退款
    @Override
    public Boolean refund(Long orderId) {
        try {
            // 1、获取：支付记录信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            // 2、添加：信息到退款记录表
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            // 3、判断：退款记录表里，当前记录是否已退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
                return true;
            }
            // 4、调用微信第三方接口，实现退款
            //（4.1）封装参数
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);   //公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);    //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());    // TODO ???
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
            // paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            // paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            //（4.2）设置，调用接口内容
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //（4.3）设置：TODO 证书信息
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            //（4.4）接收：返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("resultMap: " + resultMap);
            /*
            {
                transaction_id=4200001815202307238302314885,
                nonce_str=4ag6eI3PFsv11sx6,
                out_refund_no=tk169008428172284,
                sign=AF79B5861CEB0E59E942A587897B16C8,
                return_msg=OK,
                mch_id=1558950191,
                refund_id=50301106402023072373815273350,
                cash_fee=1,
                out_trade_no=169008428172284,
                coupon_refund_fee=0,
                refund_channel=,
                appid=wx74862e0dfcf69954,
                refund_fee=1,
                total_fee=1,
                result_code=SUCCESS,
                coupon_refund_count=0,
                cash_refund_fee=1,
                return_code=SUCCESS
            }
             */
            if (null != resultMap && WXPayConstants.SUCCESS.equals(resultMap.get("result_code"))){
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
